package startup

import (
	"gitee.com/cristiane/micro-mall-search-cron/vars"
	es7 "github.com/elastic/go-elasticsearch/v7"
	"log"
	"strings"
)

// SetupVars 加载变量
func SetupVars() error {
	var err error
	if vars.ElasticsearchSetting != nil {
		if vars.ElasticsearchSetting.Addresses != "" {
			cfg := es7.Config{
				Addresses: strings.Split(vars.ElasticsearchSetting.Addresses, ","),
				Username:  vars.ElasticsearchSetting.Username,
				Password:  vars.ElasticsearchSetting.Password,
			}
			vars.ElasticsearchClient, err = es7.NewClient(cfg)
			if err != nil {
				log.Fatalf("Config elasticsearch err: %v\n", err)
			}
			res, err := vars.ElasticsearchClient.Info()
			if err != nil {
				log.Fatalf("Load elasticsearch info response err: %s\n", err)
			}
			defer res.Body.Close()
			if res.IsError() {
				log.Fatalf("Elasticsearch error: %s\n", res.String())
			}
			log.Printf("Elasticsearch info: %+v\n", res)
			log.Println("Config elasticsearch ok")
		}
	}

	return nil
}
